package com.mitgroup.dmrvs.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;

import org.json.JSONObject;
import org.json.JSONTokener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class DispDianoseResultActivity extends AppCompatActivity {
    private static final int MSG_GET_IS_EXIST_WORK_ORDER= 1;
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private static final String BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER = "get_is_exist_work_order";
    private static final String BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_SUCCESS= "get_is_exist_work_order_success";
    private static final String BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_FAIL= "get_is_exist_work_order_fail";
    private String product;
    private Intent intent;
    /**handler对象*/
    private Handler handler;
    private ProgressDialog progressDialog;
    private String carInfoId;
    @BindView(R.id.btn_back)
    public Button back;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }

    @BindView(R.id.tv_receive_time)
    public TextView tvReceiveTime;
    @BindView(R.id.tv_car_vin)
    public TextView tvCarVin;
    @BindView(R.id.tv_car_brand)
    public TextView tvCarBrand;

    @BindView(R.id.tv_family_name)
    public TextView tvFamilyName;
    @BindView(R.id.tv_year_pattern)
    public TextView tvYearPattern;
    @BindView(R.id.tv_engine_desc)
    public TextView tvEngineDesc;
    @BindView(R.id.tv_gearbox_name)
    public TextView tvGearboxName;
    @BindView(R.id.tv_fuel_jet_type)
    public TextView tvFuelJetType;
    @BindView(R.id.tv_supply_oil)
    public TextView tvSupplyOil;
    @BindView(R.id.tv_vehicle_name)
    public TextView tvVehicleName;

    @BindView(R.id.tv_plate_number)
    public TextView tvPlateNumber;
    @BindView(R.id.tv_buy_car_time)
    public TextView tvBuyCarTime;
    @BindView(R.id.tv_mileage1)
    public TextView tvMileage;
    @BindView(R.id.tv_item_1)
    public TextView tvItem1;
    @BindView(R.id.tv_suggest_1)
    public TextView tvSuggest1;
    @BindView(R.id.tv_item_2)
    public TextView tvItem2;
    @BindView(R.id.tv_suggest_2)
    public TextView tvSuggest2;
    @BindView(R.id.tv_item_3)
    public TextView tvItem3;
    @BindView(R.id.tv_suggest_3)
    public TextView tvSuggest3;
    @BindView(R.id.tv_item_4)
    public TextView tvItem4;
    @BindView(R.id.tv_suggest_4)
    public TextView tvSuggest4;
    @BindView(R.id.tv_suggest_5)
    public TextView tvSuggest5;
    @BindView(R.id.tv_suggest_6)
    public TextView tvSuggest6;
//    @BindView(R.id.iv_intake_img)
//    public ImageView ivIntakeImg;
//    @BindView(R.id.iv_ac_img)
//    public ImageView ivAcImg;
//    @BindView(R.id.iv_fuel_img)
//    public ImageView ivFuelImg;
//    @BindView(R.id.iv_twc_img)
//    public ImageView ivTwcImg;
    @BindView(R.id.tv_intake_level_1)
    public TextView tvInTakeLevel1;
    @BindView(R.id.tv_intake_level_2)
    public TextView tvInTakeLevel2;
    @BindView(R.id.tv_intake_level_3)
    public TextView tvInTakeLevel3;
    @BindView(R.id.tv_intake_level_4)
    public TextView tvInTakeLevel4;
    @BindView(R.id.tv_intake_level_5)
    public TextView tvInTakeLevel5;
    @BindView(R.id.tv_fuel_level_1)
    public TextView tvFuelLevel1;
    @BindView(R.id.tv_fuel_level_2)
    public TextView tvFuelLevel2;
    @BindView(R.id.tv_fuel_level_3)
    public TextView tvFuelLevel3;
    @BindView(R.id.tv_fuel_level_4)
    public TextView tvFuelLevel4;
    @BindView(R.id.tv_fuel_level_5)
    public TextView tvFuelLevel5;
    @BindView(R.id.tv_twc_level_1)
    public TextView tvTwcLevel1;
    @BindView(R.id.tv_twc_level_2)
    public TextView tvTwcLevel2;
    @BindView(R.id.tv_twc_level_3)
    public TextView tvTwcLevel3;
    @BindView(R.id.tv_twc_level_4)
    public TextView tvTwcLevel4;
    @BindView(R.id.tv_twc_level_5)
    public TextView tvTwcLevel5;
    @BindView(R.id.tv_ac_level_1)
    public TextView tvAcLevel1;
    @BindView(R.id.tv_ac_level_2)
    public TextView tvAcLevel2;
    @BindView(R.id.tv_ac_level_3)
    public TextView tvAcLevel3;
    @BindView(R.id.tv_ac_level_4)
    public TextView tvAcLevel4;
    @BindView(R.id.tv_ac_level_5)
    public TextView tvAcLevel5;
    @BindView(R.id.btn_generate_order)
    public Button btnGenerateOrder;
    @OnClick(R.id.btn_generate_order)
    public void onGeneratorOrder(View view) {
        Intent   intent = new Intent(DispDianoseResultActivity.this,
                GenerateOrderActivity.class);
        intent.putExtra("carInfoId", carInfoId);
        intent.putExtra("orderItem", orderItem.toString());
        startActivity(intent);
    }
    @BindView(R.id.btn_update_order)
    public Button btnUpdateOrder;
    @OnClick(R.id.btn_update_order)
    public void onUpdateOrder(View view) {
        Intent   intent = new Intent(DispDianoseResultActivity.this,
                UpdateWorkOrderActivity.class);
        intent.putExtra("carInfoId", carInfoId);
        startActivity(intent);
    }
    @BindView(R.id.btn_disp_order)
    public Button btnDispOrder;
    @OnClick(R.id.btn_disp_order)
    public void onDispOrder(View view) {
        Intent   intent = new Intent(DispDianoseResultActivity.this,
                DispWorkOrderActivity.class);
        intent.putExtra("carInfoId", carInfoId);
        startActivity(intent);
    }
    @BindView(R.id.btn_recommend_products)
    public Button btnRecommendProducts;
    @OnClick(R.id.btn_recommend_products)
    public void onRecommendProducts(View view) {
        Intent   intent = new Intent(DispDianoseResultActivity.this,
                RecommendProductsActivity.class);
        intent.putExtra("product", product);
        startActivity(intent);
    }
    public StringBuilder orderItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_disp_dianose_result);
        ButterKnife.bind(this);
        initView();
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
        String userId=PreferencesUtils.getString(DispDianoseResultActivity.this, "userId");

        String userName = PreferencesUtils.getString(DispDianoseResultActivity.this, "userName");
        tvUserName.setText(userName);

        Intent intent = getIntent();
          carInfoId=intent.getStringExtra("carInfoId");
        getIsExistWorkOrder(carInfoId);
        String receiveTime = intent.getStringExtra("receiveTime");
        String carVin=intent.getStringExtra("carVin");
        String carBrand = intent.getStringExtra("carBrand");
        String familyName=intent.getStringExtra("familyName");
        String engineDesc=intent.getStringExtra("engineDesc");
        String yearPattern=intent.getStringExtra("yearPattern");
        String gearboxName=intent.getStringExtra("gearboxName");
        String fuelJetType=intent.getStringExtra("fuelJetType");
        String supplyOil=intent.getStringExtra("supplyOil");
        String vehicleName=intent.getStringExtra("vehicleName");
        String plateNumber = intent.getStringExtra("plateNumber");
        String buyCarTime = intent.getStringExtra("buyCarTime");
        String mileage = intent.getStringExtra("mileage");
        String diagnoseResult = intent.getStringExtra("diagnoseResult");
        product = intent.getStringExtra("product");
        String intakeLevel=intent.getStringExtra("intakeLevel");
        if("正常".equals(intakeLevel))
        {
            tvInTakeLevel1.setText("正常 ☑");
            tvInTakeLevel1.setTextColor(Color.BLUE);
        }
        else  if("轻度".equals(intakeLevel))
        {
            tvInTakeLevel2.setText("轻度 ☑");
            tvInTakeLevel2.setTextColor(Color.BLUE);
        }
        else  if("中度".equals(intakeLevel))
        {
            tvInTakeLevel3.setText("中度 ☑");
            tvInTakeLevel3.setTextColor(Color.BLUE);
        }
        else  if("重度".equals(intakeLevel))
        {
            tvInTakeLevel4.setText("重度 ☑");
            tvInTakeLevel4.setTextColor(Color.BLUE);
        }
        else  if("其他".equals(intakeLevel))
        {
            tvInTakeLevel5.setText("其他 ☑");
            tvInTakeLevel5.setTextColor(Color.BLUE);
        }
        String fuelLevel=intent.getStringExtra("fuelLevel");
        if("正常".equals(fuelLevel))
        {
            tvFuelLevel1.setText("正常 ☑");
            tvFuelLevel1.setTextColor(Color.BLUE);
        }
        else  if("轻度".equals(fuelLevel))
        {
            tvFuelLevel2.setText("轻度 ☑");
            tvFuelLevel2.setTextColor(Color.BLUE);
        }
        else  if("中度".equals(fuelLevel))
        {
            tvFuelLevel3.setText("中度 ☑");
            tvFuelLevel3.setTextColor(Color.BLUE);
        }
        else  if("重度".equals(fuelLevel))
        {
            tvFuelLevel4.setText("重度 ☑");
            tvFuelLevel4.setTextColor(Color.BLUE);
        }
        else  if("其他".equals(fuelLevel))
        {
            tvFuelLevel5.setText("其他 ☑");
            tvFuelLevel5.setTextColor(Color.BLUE);
        }
        String twcLevel=intent.getStringExtra("twcLevel");
        if("正常".equals(twcLevel))
        {
            tvTwcLevel1.setText("正常 ☑");
            tvTwcLevel1.setTextColor(Color.BLUE);
        }
        else  if("轻度".equals(twcLevel))
        {
            tvTwcLevel2.setText("轻度 ☑");
            tvTwcLevel2.setTextColor(Color.BLUE);
        }
        else  if("中度".equals(twcLevel))
        {
            tvTwcLevel3.setText("中度 ☑");
            tvTwcLevel3.setTextColor(Color.BLUE);
        }
        else  if("重度".equals(twcLevel))
        {
            tvTwcLevel4.setText("重度 ☑");
            tvTwcLevel4.setTextColor(Color.BLUE);
        }
        else  if("其他".equals(twcLevel))
        {
            tvTwcLevel5.setText("其他 ☑");
            tvTwcLevel5.setTextColor(Color.BLUE);
        }
        String acLevel=intent.getStringExtra("acLevel");
        if("正常".equals(acLevel))
        {
            tvAcLevel1.setText("正常 ☑");
            tvAcLevel1.setTextColor(Color.BLUE);
        }
        else  if("轻度".equals(acLevel))
        {
            tvAcLevel2.setText("轻度 ☑");
            tvAcLevel2.setTextColor(Color.BLUE);
        }
        else  if("中度".equals(acLevel))
        {
            tvAcLevel3.setText("中度 ☑");
            tvAcLevel3.setTextColor(Color.BLUE);
        }
        else  if("重度".equals(acLevel))
        {
            tvAcLevel4.setText("重度 ☑");
            tvAcLevel4.setTextColor(Color.BLUE);
        }
        else  if("其他".equals(acLevel))
        {
            tvAcLevel5.setText("其他 ☑");
            tvAcLevel5.setTextColor(Color.BLUE);
        }
        tvReceiveTime.setText(receiveTime);
        tvPlateNumber.setText(plateNumber);
        tvCarVin.setText(carVin);
        tvCarBrand.setText(carBrand);
        tvFamilyName.setText(familyName);
        tvEngineDesc.setText(engineDesc);
        tvYearPattern.setText(yearPattern);
        tvGearboxName.setText(gearboxName);
        tvFuelJetType.setText(fuelJetType);
        tvSupplyOil.setText(supplyOil);
        tvVehicleName.setText(vehicleName);
        tvBuyCarTime.setText(buyCarTime);
        tvMileage.setText(mileage);

        if(diagnoseResult!=null && !"".equals(diagnoseResult))
        {
            try {
                String[] diagnoseResultArr=diagnoseResult.split("\\|");
                orderItem=new StringBuilder();
                for(int i=0;i<diagnoseResultArr.length;i++)
                {
                    String resultItemStr=diagnoseResultArr[i];
                    String[] resultItem=resultItemStr.split(":");
                    String resultItem1=resultItem[0];
                    String resultItem2=resultItem[1];
                    if("A".equals(resultItem1))
                    {
                       tvItem1.setText(resultItem2);
                       tvSuggest1.setText("建议检查并清洗润滑系统");
                       orderItem.append("A,");//润滑系统保养
                    }
                    else if("B".equals(resultItem1))
                    {
                        tvItem2.setText(resultItem2);
                        tvSuggest2.setText("建议检查并清洗排放系统和三元催化转换器");
                        orderItem.append("B,");//排放系统保养
                    }
                    else if("C".equals(resultItem1))
                    {
                        tvItem3.setText(resultItem2);
                        tvSuggest3.setText("建议检查并清洗节气门体，进气门，燃烧室");
                        orderItem.append("C,");//燃油系统保养，节气门保养
                    }
                    else if("D".equals(resultItem1))
                    {
                        tvItem4.setText(resultItem2);
                        tvSuggest4.setText("建议检查并清洗自动变速箱系统，液压转向系统，冷却系统");
                        orderItem.append("D,");//自动变速箱系统保养，液压转向系统，冷却系统系统保养
                    }
                    else if("E".equals(resultItem1))
                    {

                        tvSuggest5.setText("建议检查并清洗蒸发箱和空调系统");
                        orderItem.append("E,");//蒸发箱和空调系统保养
                    }
                    else if("F".equals(resultItem1))
                    {
                        tvSuggest6.setText("检查并清洗润滑系统");
                        orderItem.append("F,");//润滑系统保养
                    }
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

    }
    private Handler myHandler = new Handler() {
        String key="";
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            String key="";
            switch (msg.what) {

                case MSG_GET_IS_EXIST_WORK_ORDER:
                    key= msg.getData().keySet().iterator().next();
                    if (BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(DispDianoseResultActivity.this,"服务器连接失败！", Toast.LENGTH_SHORT).show();

                    }

                    else if (BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_SUCCESS.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        String content=msg.getData().getString(BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_SUCCESS);
                        if(!"".equals(content))
                        {
                            if("0".equals(content))
                            {
                                btnUpdateOrder.setEnabled(false);
                                btnUpdateOrder.setBackgroundResource(R.drawable.button_small_cancle);
                                btnDispOrder.setEnabled(false);
                                btnDispOrder.setBackgroundResource(R.drawable.button_small_cancle);
                            }
                            else
                            {
                                btnGenerateOrder.setEnabled(false);
                                btnGenerateOrder.setBackgroundResource(R.drawable.button_small_cancle);
                            }

                        }

                    }
                    break;

                default:
                    break;
            }
            removeMessages(msg.what);
        }
    };
   protected void getIsExistWorkOrder(String carInfoId){
       if(Utils.isNetworkAvailable(DispDianoseResultActivity.this)==false)
       {
           Toast.makeText(DispDianoseResultActivity.this,"网络尚未连接，请连接网络！",Toast.LENGTH_SHORT).show();
           return;
       }

       final String []key={"carInfoId"};
       final String []value={carInfoId};
       progressDialog = ProgressDialog.show(DispDianoseResultActivity.this,
               getResources().getString(R.string.notice), "正在加载中...");
       new Thread(new Runnable() {
           @Override
           public void run() {
               Bundle bundle = new Bundle();
               try {
                   String rs = WSClient.soapGetInfo("getIsExistWorkOrder",key,value);
                   JSONTokener jsonTokener = new JSONTokener(rs);
                   JSONObject jsonObject = (JSONObject) jsonTokener
                           .nextValue();
                   String status = jsonObject.getString("status");
                   String content = jsonObject.get("content").toString();
                   if("1".equals(status))						{

                       bundle.putString(BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_SUCCESS,content);
                   }
                   else
                   {
                       bundle.putString(BUNDLE_MSG_GET_IS_EXIST_WORK_ORDER_FAIL, "加载失败，请重试！");
                   }
               }
               catch (Exception e) {

                   bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
               }
               Message msg = myHandler.obtainMessage();
               msg.what = MSG_GET_IS_EXIST_WORK_ORDER;
               msg.setData(bundle);
               myHandler.sendMessage(msg);
           }
       }).start();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }
}
